import { Component, OnInit, Input } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { _HttpClient } from '@delon/theme';
import { Observable } from 'rxjs';

@Component({
  selector: 'edit-base-type-values',
  templateUrl: './edit-base-type-values.component.html',
  styles: [`
    :host ::ng-deep .form-inner {
      padding: 16px 40px 0;
    }
    :host ::ng-deep .label-width {
      width: 100px;
    }
  `]
})
export class EditBaseTypeValuesComponent implements OnInit {

  public validateForm: FormGroup;

  @Input() public value: any;
  @Input() public key: any;

  constructor(
    private formBuilder: FormBuilder,
    private http: _HttpClient
  ) { }

  public ngOnInit() {
    const value: any = this.value || {};

    this.validateForm = this.formBuilder.group({
      sequence: [value.sequence || null, [Validators.required]],
      baseTypeValue: [value.baseTypeValue || null, [Validators.required]],
      description: [value.description || null]
    });
  }

  public hasError(controlName: string): boolean {
    return !!(
      this.validateForm.get(controlName).dirty &&
      this.validateForm.get(controlName).errors
    );
  }

  public submit(): Observable<any> {
    for (const item in this.validateForm.controls) {
      this.validateForm.controls[item].markAsDirty();
      this.validateForm.controls[item].updateValueAndValidity();
    }

    if (this.validateForm.valid) {
      const apiValues: string = '/api/base-type-values';
      let params: any = Object.assign({}, this.validateForm.value);
      params.baseTypeKeyId = this.key.id;

      if (this.value) {
        params.id = this.value.id;
        return this.http.put(apiValues, params);
      } else {
        return this.http.post(apiValues, params);
      }

    } else {
      return new Observable(observer => observer.complete());
    }
  }

}
